package com.rongc.client.freight.base.view.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.widget.ScrollView;

import com.android.volley.Response;
import com.android.volley.error.VolleyError;
import com.flyco.animation.ZoomEnter.ZoomInEnter;
import com.flyco.animation.ZoomExit.ZoomOutExit;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.rongc.client.core.network.code.HandleCode;
import com.rongc.client.core.network.http.RequestManager;
import com.rongc.client.core.utils.ActivityUtils;
import com.rongc.client.core.utils.LogUtils;
import com.rongc.client.core.utils.StringUtils;
import com.rongc.client.freight.R;
import com.rongc.client.freight.UniApplication;
import com.rongc.client.freight.base.BaseFragment;
import com.rongc.client.freight.base.model.BaseDic;
import com.rongc.client.freight.base.request.api.BannerApi;
import com.rongc.client.freight.base.request.api.IsAuthApi;
import com.rongc.client.freight.base.request.api.TypeApi;
import com.rongc.client.freight.base.request.api.UnReadApi;
import com.rongc.client.freight.base.request.result.BannerResult;
import com.rongc.client.freight.base.request.result.NullResult;
import com.rongc.client.freight.base.view.adapter.RecyclerBaseAdapter;
import com.rongc.client.freight.base.view.adapter.RecyclerMainAdapter;
import com.rongc.client.freight.base.view.widget.AutoBanner;
import com.rongc.client.freight.base.view.widget.DividerItemDecoration;
import com.rongc.client.freight.base.view.widget.EmptyRecyclerView;
import com.rongc.client.freight.base.view.widget.IDDialog;
import com.rongc.client.freight.business.carrier.model.ConveyanceDic;
import com.rongc.client.freight.business.carrier.view.activity.ConveyanceCreateActivity;
import com.rongc.client.freight.business.carrier.view.activity.ConveyanceSupplyListActivity;
import com.rongc.client.freight.business.mine.view.activity.AuthHostActivity;
import com.rongc.client.freight.business.supply.model.SupplyDic;
import com.rongc.client.freight.business.supply.view.activity.SupplyConveyanceListActivity;
import com.rongc.client.freight.business.supply.view.activity.SupplyCreateActivity;
import com.rongc.client.freight.business.waybill.model.WayBillBean;
import com.rongc.client.freight.business.waybill.model.WayBillList;
import com.rongc.client.freight.business.waybill.request.api.HostWayBillApi;
import com.rongc.client.freight.business.waybill.request.api.HostWayBillSJApi;
import com.rongc.client.freight.business.waybill.view.activity.WaybillListMainActivity;
import com.rongc.client.freight.business.waybill.view.adapter.RecyclerWaybillListAdapter;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.OnClick;

import static com.flyco.dialog.widget.NormalDialog.STYLE_TWO;

/**
 * Created by Bruce on 2017/06/29.
 */
public class HomeFragment extends BaseFragment implements View.OnClickListener{
    @Bind(R.id.sv_body)
    PullToRefreshScrollView scrollView;
    @Bind(R.id.auto_banner)
    AutoBanner autoBanner;
    @Bind(R.id.recycler)
    RecyclerView mRecyclerView;
    @Bind(R.id.recycler_list)
    EmptyRecyclerView mRvBot;
    @Bind(R.id.id_empty_view)
    View mEmptyView;

    RecyclerWaybillListAdapter mLvAdapter;
    RecyclerMainAdapter mRecyclerAdapter;

    List<HashMap<String,String>> lsOperate;

    List<BannerResult> lsBanners;
    List<WayBillBean> lsNews;
    IDDialog dialog;

    NormalDialog authDialog;
    String type;
    Timer timer = new Timer(); ;

    public static HomeFragment getInstance(){
        /*if(fragment == null) fragment = new HomeFragment(orderType);
        return fragment;*/
        HomeFragment fragment = new HomeFragment();
        Bundle bdl = new Bundle();
//        bdl.putString("orderType", orderType);
        fragment.setArguments(bdl);
        return fragment;
    }

    @OnClick({R.id.toolbar_title,R.id.tv_more,R.id.tv_tip})
    @Override
    public void onClick(View v) {
        if(!checkType()) return;

        switch (v.getId()){
            case R.id.tv_tip:
                ActivityUtils.callToContact(getActivity());
                break;
            case R.id.toolbar_title:
//                dialog.show();
                break;
            case R.id.tv_more:
                ActivityUtils.startActivity(getActivity(),WaybillListMainActivity.class);
                break;
        }
    }

    boolean checkType(){
        if(!UniApplication.getInstance().hasType()){
            dialog.show();
            return false;
        }
        return true;
    }

    Response.Listener<NullResult> respTypeListener = new Response.Listener<NullResult>() {

        @Override
        public void onResponse(NullResult response) {
            if (HandleCode.requestSuccess()) {
                UniApplication.getInstance().getUserInfo().setType(type);
                UniApplication.getInstance().getUserInfo().save();
                initData();
            }
        }
    };

    Response.Listener<JSONObject> respUnReadListener = new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            if (HandleCode.requestSuccess()) {
                if(response != null && response.optBoolean("hasUnRead")){
                    Intent intent = new Intent("com.rongc.client.freight");
                    intent.putExtra("unRead",true);
                    getActivity().sendBroadcast(intent);
                }else{
                    Intent intent = new Intent("com.rongc.client.freight");
                    intent.putExtra("unRead",false);
                    getActivity().sendBroadcast(intent);
                }

            }
        }
    };

    Response.Listener<WayBillList> respNewsListener = new Response.Listener<WayBillList>() {

        @Override
        public void onResponse(WayBillList response) {
            if (HandleCode.requestSuccess()) {
                if(response != null && response.getList() != null){
                    lsNews.clear();
                    lsNews.addAll(response.getList());
                    mLvAdapter.notifyDataSetChanged();
                }

//                mLvAdapter.notifyDataSetChanged();
            }

            if(lsNews == null || lsNews.size()==0)
                mRvBot.setEmptyView(mEmptyView);
            scrollView.onRefreshComplete();
        }
    };

    Response.Listener<JSONObject> respAuthListener = new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            if (HandleCode.requestSuccess()) {
                if(response != null ){
                    UniApplication.getInstance().getUserInfo().setAuthStatus(response.optString("status"));
                    UniApplication.getInstance().getUserInfo().save();
                }
            }
        }
    };

    Response.Listener<BannerResult[]> respBannerListener = new Response.Listener<BannerResult[]>() {

        @Override
        public void onResponse(BannerResult[] response) {
            if (HandleCode.requestSuccess()) {
                if (response != null && response.length != 0) {
                    lsBanners.clear();
                    for (int i = 0; i < response.length; i++) {
                        lsBanners.add(response[i]);
                    }
                }
                List<String> imgesUrl = new ArrayList<>();
                List<Integer> imageUrl = new ArrayList<>();
                for (BannerResult r: lsBanners) {
                    imgesUrl.add(/*ApiUrl.getDefaultHost() + */r.getUrl());
                }
                if(imgesUrl.size() == 0) {
                    imageUrl.add(R.mipmap.default_banner);
                    imageUrl.add(R.mipmap.default_banner2);
                    autoBanner.setImages(imageUrl);
                }else{
                    autoBanner.setImagesUrl(imgesUrl);
                }
                autoBanner.setOnItemClickListener(new AutoBanner.OnItemClickListener() {
                    @Override
                    public void onItemClick(int position) {
                        if(lsBanners.size() > position) {
                            BannerResult homeBannerResult = lsBanners.get(position);
                            ActivityUtils.jumpBrowser(getActivity(), homeBannerResult.getJumpUrl());
                        }
                    }
                });

//                mVpAdapter.notifyDataSetChanged();
            }
        }
    };

    Response.ErrorListener errorListener = new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            mRvBot.setEmptyView(mEmptyView);
            scrollView.onRefreshComplete();
            LogUtils.i("error.getMessage(): " + error.getMessage());
        }
    };

    @Override
    public void onAuth() {
        switch (UniApplication.getInstance().getType()) {
            case BaseDic.IdentityType.DRIVING_TYPE:
                if(UniApplication.getInstance().isAuth()) {
                    ActivityUtils.startActivity(getActivity(),ConveyanceCreateActivity.class);
                }else{
                    if(UniApplication.getInstance().isAuthIng())
                        ActivityUtils.toast("您已提交申请，还在审核当中");
                    else
                        authDialog.show();
                }
                break;
            case BaseDic.IdentityType.OWNER_TYPE:
                if(UniApplication.getInstance().isAuth()) {
                    ActivityUtils.startActivity(getActivity(),SupplyCreateActivity.class);
                }else{
                    if(UniApplication.getInstance().isAuthIng())
                        ActivityUtils.toast("您已提交申请，还在审核当中");
                    else
                        authDialog.show();
                }
                break;
        }
    }

    @Override
    public void initListener() {

        mRecyclerAdapter.setOnItemClickListener(new RecyclerBaseAdapter.OnItemClickListener<HashMap<String, String>>() {
            @Override
            public void onItemClick(View view, int position, HashMap<String, String> data) {
                if(!checkType()) return;
                switch (data.get("type")){
                    case BaseDic.OperateType.SHIPPER_CREATE_TYPE:
                        if(UniApplication.getInstance().isAuth()) {
                            ActivityUtils.startActivity(getActivity(),SupplyCreateActivity.class);
                        }else{
                            doAuth();
                        }
                        break;
                    case BaseDic.OperateType.SHIPPER_FIND_TYPE:
                        ActivityUtils.startActivity(getActivity(), SupplyConveyanceListActivity.class);
                        break;
                    case BaseDic.OperateType.CARRIER_CREATE_TYPE:
                        if(UniApplication.getInstance().isAuth()) {
                            ActivityUtils.startActivity(getActivity(),ConveyanceCreateActivity.class);
                        }else{
                            doAuth();
                        }

                        break;
                    case BaseDic.OperateType.CARRIER_FIND_TYPE:
                        ActivityUtils.startActivity(getActivity(),ConveyanceSupplyListActivity.class);
                        break;
                }
            }
        });

        scrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ScrollView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
                showData();
            }
        });

    }

    public void showData(){
        switch (UniApplication.getInstance().getType()) {
            case BaseDic.IdentityType.DRIVING_TYPE:
                authDialog.content(getResources().getString(R.string.auth_driving_create_label));
                RequestManager.getInstance().call(new HostWayBillSJApi(new HostWayBillSJApi.HostWayBillSJParams(
                        UniApplication.getInstance().getUserInfo().getUserId(),"1","1"),
                        respNewsListener, errorListener));
                break;
            case BaseDic.IdentityType.OWNER_TYPE:
                authDialog.content(getResources().getString(R.string.auth_create_label));
                RequestManager.getInstance().call(new HostWayBillApi(new HostWayBillApi.HostWayBillParams(
                        UniApplication.getInstance().getUserInfo().getUserId(),"1","1"),
                        respNewsListener, errorListener));
                break;
        }

        RequestManager.getInstance().call(new UnReadApi(new UnReadApi.UnReadParams(),
                respUnReadListener, errorListener));
    }

    @Override
    public void initData() {

        RequestManager.getInstance().call(new IsAuthApi(new IsAuthApi.IsAuthParams(),
                respAuthListener, errorListener));

        RequestManager.getInstance().call(new BannerApi(new BannerApi.BannerParams(),
                respBannerListener, errorListener));

        lsOperate.clear();
        switch (UniApplication.getInstance().getType()){
            case BaseDic.IdentityType.DRIVING_TYPE:
//                initToolbar(R.string.main_title_carrier);
                HashMap<String, String> operate = new HashMap<String, String>();
                operate.put("type",BaseDic.OperateType.CARRIER_CREATE_TYPE);
                lsOperate.add(operate);
                operate = new HashMap<String, String>();
                operate.put("type",BaseDic.OperateType.CARRIER_FIND_TYPE);
                lsOperate.add(operate);
                break;
            case BaseDic.IdentityType.OWNER_TYPE:
//                initToolbar(R.string.main_title_shipper);
                operate = new HashMap<String, String>();
                operate.put("type",BaseDic.OperateType.SHIPPER_CREATE_TYPE);
                lsOperate.add(operate);
                operate = new HashMap<String, String>();
                operate.put("type",BaseDic.OperateType.SHIPPER_FIND_TYPE);
                lsOperate.add(operate);
                break;
        }
        showData();
        mLvAdapter.notifyDataSetChanged();
        mRecyclerAdapter.notifyDataSetChanged();

        if(!isrun)
            timer.schedule(task,500,5000);
    }


    TimerTask task= new TimerTask() {
        @Override
        public void run() {
            isrun = true;
            if(isShow())
                showData();
        }
    };

    boolean isrun = false;


    @Override
    public void onDestroy() {
        super.onDestroy();
        timer.cancel();
    }

    @Override
    public void initView() {
        initToolbar(R.string.app_name);
        lsNews = new ArrayList<>();
        lsBanners = new ArrayList<>();
        lsOperate = new ArrayList<>();

//        DateUtil.checkError();

        mLvAdapter = new RecyclerWaybillListAdapter(getActivity(), lsNews);
        mRvBot.setLayoutManager(new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false));
        mRvBot.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
        mRvBot.setAdapter(mLvAdapter);

        mRecyclerAdapter = new RecyclerMainAdapter(getActivity(),lsOperate);

        mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(),2));
        mRecyclerView.setAdapter(mRecyclerAdapter);


        dialog = new IDDialog(getActivity());
        dialog.contentTextSize(14)
                .contentTextColor(Color.parseColor("#444444"))
                .contentGravity(Gravity.CENTER)
                .showAnim(new ZoomInEnter())
                .dismissAnim(new ZoomOutExit())
                .cornerRadius(8)
                .dimEnabled(true)
                .setCanceledOnTouchOutside(false);
        dialog.setOnBtnClickL(new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                type = BaseDic.IdentityType.OWNER_TYPE;
                RequestManager.getInstance().call(new TypeApi(new TypeApi.TypeParams(
                        type),
                        respTypeListener, errorListener));
                dialog.dismiss();
            }
        }, new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                type = BaseDic.IdentityType.DRIVING_TYPE;
                RequestManager.getInstance().call(new TypeApi(new TypeApi.TypeParams(
                        type),
                        respTypeListener, errorListener));
                dialog.dismiss();
            }
        });


        makeAuth();
        mLvAdapter.setOnItemClickListener(new RecyclerBaseAdapter.OnItemClickListener<WayBillBean>() {
            @Override
            public void onItemClick(View view, int position, WayBillBean data) {
                if(!checkType()) return;
                switch (UniApplication.getInstance().getType()) {
                    case BaseDic.IdentityType.DRIVING_TYPE:
                        ConveyanceDic.jumpActivity(getActivity(), StringUtils.parseInt(data.getWaystate()),data);
                        break;
                    case BaseDic.IdentityType.OWNER_TYPE:
                        SupplyDic.jumpActivity(getActivity(),StringUtils.parseInt(data.getWaystate()),data);
                        break;
                }
            }
        });

        checkType();


    }

    void makeAuth(){
        authDialog = new NormalDialog(getActivity());
        authDialog.title(getResources().getString(R.string.auth_dialog_title))
                .content(getResources().getString(R.string.auth_create_label))
                .style(STYLE_TWO)
                .btnText(new String[]{"取消","立即认证"})
                .setOnBtnClickL(new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        authDialog.cancel();
                    }
                },new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        ActivityUtils.startActivity(getActivity(), AuthHostActivity.class);
                        authDialog.cancel();
                    }
                });
    }


    @Override
    public int getLayoutId() {
        return R.layout.fragment_host_home;
    }
}
